﻿# coding=utf-8
import os
import sys
import re
#reload(sys)
#sys.setdefaultencoding("utf-8")

sys.path.append(r'E:\vmware\models-master\research\slim\keras-yolov3-master')

import time
from flask import request, send_from_directory
from flask import Flask, request, redirect, url_for
import uuid
import tensorflow as tf
from classify_image import run_inference_on_image

import yolo_video
 
ALLOWED_EXTENSIONS = set(['jpg','JPG', 'jpeg', 'JPEG', 'png'])
 
FLAGS = tf.app.flags.FLAGS
 
tf.app.flags.DEFINE_string('model_dir', '', """Path to graph_def pb, """)
tf.app.flags.DEFINE_string('model_name', 'E:\\vmware\\models-master\\research\\slim\\frozen_graph.pb', '')
tf.app.flags.DEFINE_string('label_file', 'E:\\vmware\\models-master\\research\\slim\\tmp\\pj_vehicle\\labels.txt', '')
tf.app.flags.DEFINE_string('upload_folder', '/tmp/', '')
tf.app.flags.DEFINE_integer('num_top_predictions', 5,
                            """Display this many predictions.""")
tf.app.flags.DEFINE_integer('port', '5001',
        'server with port,if no port, use deault port 80')
 
tf.app.flags.DEFINE_boolean('debug', True, '')
 
#UPLOAD_FOLDER = FLAGS.upload_folder
UPLOAD_FOLDER = os.path.curdir+os.path.sep+'tmp'+os.path.sep+'upload'+os.path.sep
CROP_FOLDER = os.path.curdir+os.path.sep+'keras-yolov3-master'+os.path.sep+'images'+os.path.sep+'crop'+os.path.sep
OUT_FOLDER = os.path.curdir+os.path.sep+'keras-yolov3-master'+os.path.sep+'images'+os.path.sep+'out'+os.path.sep
ALLOWED_EXTENSIONS = set(['jpg','JPG', 'jpeg', 'JPEG', 'png'])
 
app = Flask(__name__)
app._static_folder = UPLOAD_FOLDER
 
def allowed_files(filename):
  return '.' in filename and \
      filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
 
def rename_filename(old_file_name):
  basename = os.path.basename(old_file_name)
  name, ext = os.path.splitext(basename)
  new_name = str(uuid.uuid1()) + ext
  return new_name
 
def inference(crop_image, out_path):
  # if file_name != "":
    # try:
      # predictions, top_k, top_names = run_inference_on_image(file_name, FLAGS.model_name, FLAGS.label_file)
    # except Exception as ex: 
      # print(ex)
      # return ""

  if crop_image != None:
    try:
      predictions, top_k, top_names = run_inference_on_image(crop_image, FLAGS.model_name, FLAGS.label_file)
    except Exception as ex: 
      print(ex)
      return ""      
    
  print("in:%s,out:%s"%(crop_image, out_path))  
  new_url = '/static/%s' % os.path.basename(out_path)
  image_tag = '<img src="%s"></img><p>'
  new_tag = image_tag % new_url
  format_string = ''
  
  if crop_image != None:
    for node_id, human_name in zip(top_k, top_names):
      score = predictions[node_id]
      format_string += '%s (score:%.5f)<BR>' % (human_name, score)
    ret_string = new_tag + format_string + '<BR>'
  else:
    ret_string = new_tag + "没找到汽车" + '<BR>'  
  return ret_string
 
 
@app.route("/", methods=['GET', 'POST'])
def root():
  result = """
    <!doctype html>
    <title>临时测试用</title>
    <h1>来喂一张照片吧</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file value='选择图片'>
         <input type=submit value='上传'>
    </form>
    <p>%s</p>
    """ % "<br>"
  print(request)  
  print(request.method)
  if request.method == 'POST':
    file = request.files['file']
    print('file:%s'%file)
    old_file_name = file.filename
    if file and allowed_files(old_file_name):
      filename = rename_filename(old_file_name)
      file_path = os.path.join(UPLOAD_FOLDER, filename)
      file.save(file_path)
      type_name = 'N/A'
      print('file saved to %s' % file_path)
      image_crop = yolo_video.detect_img(os.path.abspath(file_path))
#      os.system('python E:\\vmware\\models-master\\research\\slim\\keras-yolov3-master\\yolo_video.py --image_path=%s'%os.path.abspath(file_path))
      #list crop file
      # crop_path = ""
      # for file in os.listdir(CROP_FOLDER):
        # print('file:'+file)
        # print(os.path.splitext(filename)[0])
        # cropfile = re.match(os.path.splitext(filename)[0], file)
        # if cropfile is not None:
          # print(cropfile)
          # crop_path = os.path.join(CROP_FOLDER, file)
          # break
      #list out file
      output_path = os.path.join(OUT_FOLDER, filename)
      print('outpath:%s'%output_path)
        
      out_html = inference(image_crop, output_path)
      return result + out_html 
  return result
 
if __name__ == "__main__":
  print('listening on port %d' % FLAGS.port)
  app.run(host='127.0.0.1', port=FLAGS.port, debug=FLAGS.debug, threaded=True)